/* eslint-disable react/jsx-key */
import React, { useState, useRef, useMemo } from 'react';
import ReactDOM from 'react-dom';
import { Card, Switch, Button, Modal, message, Popconfirm, Tooltip } from 'antd';
import AutoTable from '@/components/AutoTable';
import InitForm from '@/components/InitForm';
import { connect } from 'umi';
import { company, companydetail } from '@/services/business';
import CompanyDetail from '@/components/CompanyDetail';
import moment from 'moment';
import CompanyName from '@/components/CompanyName';


let defaultFields = {
    effect_time: {
      value: null,
      type: 'datepicker',
      title: '生效月份',
      name: ['effect_time'],
      required: true,
      picker: 'month',
      col: { span: 24 },
      disabledDate: (current) => {
        return current && current < moment().endOf('month');
      },
    },
  },
  shFields = {
    refuse_reason: {
      value: null,
      type: 'textarea',
      title: '拒绝原因',
      name: ['refuse_reason'],
      required: true,
      col: { span: 24 },
    },
  },
  status = {
    account_pending: '会计主管录入中',
    chief_pending: '会计总监审核中',
    cancel: '总监驳回',
    completed: '已完成',
  };

function Monthchange(props) {
  const [vs, cvs] = useState(false), //表单显/隐
    [fields, cf] = useState(defaultFields),
    [iftype, ciftype] = useState({}),
    [unitprice, cp] = useState(0);

  let actionRef = useRef(),
    ChildRef = null;
  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
  }
  const columns = useMemo(() => {
    return [
      {
        title: '公司名称',
        width: 260,
        dataIndex: 'company_name',
        key: 'company_name',
        render: (_, row) => (
          <CompanyName
            row={{ ...row, name: row?.company_name ?? row?.name, id: row?.company_id ?? row?.id }}
            reload={reload}
          />
        ),
      },
      {
        title: '变更前月收费',
        dataIndex: 'origin_unit_price',
        key: 'origin_unit_price',
        search: false,
      },
      {
        title: '变更后月收费',
        dataIndex: 'unit_price',
        key: 'unit_price',
        search: false,
      },
      {
        title: '变更原因',
        dataIndex: 'reason',
        key: 'reason',
        search: false,
      },
      {
        title: '发起人',
        dataIndex: 'creator_name',
        key: 'creator_name',
        search: false,
      },
      {
        title: '审核人',
        dataIndex: 'account_user_name',
        key: 'account_user_name',
        search: false,
      },
      {
        title: '实际情况',
        dataIndex: 'actual_reason',
        key: 'actual_reason',
        search: false,
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        search: false,
        render: (_, row) => <span>{status[row.status]}</span>,
      },
      {
        title: '生效月份',
        dataIndex: 'effect_time',
        key: 'effect_time',
        search: false,
        render: (_, row) => (
          <span>{row.effect_time ? moment(row.effect_time).format('YYYY-MM') : '-'}</span>
        ),
      },
      {
        title: '驳回原因',
        dataIndex: 'refuse_reason',
        key: 'refuse_reason',
        search: false,
      },
      {
        title: '操作',
        valueType: 'option',
        width: 120,
        render: (text, record, _, action) => {
          const ifs =
            record.status != 'chief_pending' && props.currentUser.id !== record.account_user_name;
          return [
            <a
              disabled={ifs}
              style={{ color: ifs ? '#999' : '#1890ff' }}
              onClick={() => {
                if (ifs) {
                  return;
                }
                cvs(true);
                cf(() => {
                  for (let i in defaultFields) {
                    defaultFields[i].value = record[i];
                  }
                  return { ...defaultFields };
                });
                ciftype({
                  val: 'pass',
                  title: '通过',
                  id: record.id,
                });
              }}
            >
              通过
            </a>,
            <a
              disabled={ifs}
              style={{ color: ifs ? '#999' : '#1890ff' }}
              onClick={() => {
                if (ifs) {
                  return;
                }
                cvs(true);
                cf(() => {
                  for (let i in shFields) {
                    shFields[i].value = record[i];
                  }
                  return { ...shFields };
                });
                ciftype({
                  val: 'nopass',
                  title: '驳回',
                  id: record.id,
                });
              }}
            >
              驳回
            </a>,
          ];
        },
      },
    ];
  }, []);

  let saveData = (values) => {
    let { dispatch } = props;
    if (iftype.val == 'pass') {
      values.effect_time = moment(values.effect_time)
        .startOf('month')
        .format('YYYY-MM-DD HH:mm:ss');
      dispatch({
        type: 'customer/chief_agree',
        payload: { ...values, id: iftype.id },
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
        }
      });
    } else if (iftype.val == 'nopass') {
      dispatch({
        type: 'customer/chief_refuse',
        payload: { ...values, id: iftype.id },
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
        }
      });
    }
  };

  return (
    <div className="pgcontainer">
      <AutoTable
        pagetitle={props.route.name} //页面标题
        columns={columns}
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
        path="/wbn-api/month_charge"
        //withCard={false}
        //cardtitle = "name" //卡片标题
        //cardavatar = "img_url" //卡片头像
      ></AutoTable>
      <Modal
        maskClosable={false}
        title={iftype.title}
        open={vs}
        onCancel={() => cvs(false)}
        footer={false}
        width={iftype.val == 'detail' ? 1200 : 600}
        destroyOnClose={true}
      >
        {iftype.val == 'detail' ? (
          <CompanyDetail id={iftype.id || ''}></CompanyDetail>
        ) : (
          <div>
            {iftype.val == 'add' && (
              <p style={{ marginBottom: 0 }}>当前选择公司的月收费：{unitprice}</p>
            )}
            <InitForm
              fields={fields}
              submitData={(values) => {
                saveData(values);
              }}
              onChange={(changedValues, allValues) => {
                //联动操作
                let label = Object.keys(changedValues)[0],
                  value = Object.values(changedValues)[0];
                if (label == 'company_id') {
                  companydetail({ id: value }).then((res) => {
                    cp(res?.data?.unit_price ?? 0);
                  });
                }
              }}
              submitting={
                props.loading.effects['customer/chief_refuse'] ||
                props.loading.effects['customer/editrescind'] ||
                !vs
              }
            ></InitForm>
          </div>
        )}
      </Modal>
    </div>
  );
}

export default connect(({ customer, loading, user }) => ({
  customer,
  loading,
  currentUser: user.currentUser,
}))(Monthchange);
